import pika
import uuid


class ProcessMain(object):
    """
    主进程
    """

    def __init__(self):
        self.response = None
        self.corr_id = str(uuid.uuid4())

        self.connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
        self.channel = self.connection.channel()
        self.callback_queue = self.channel.queue_declare('sub_process_result')
        self.channel.basic_consume('sub_process_result', self.on_response, True)

    def on_response(self, ch, method, props, body):
        print(f'Accept Data From Sub Process:{body}')
        if self.corr_id == props.correlation_id:
            self.response = body

    def call_sub_process(self, obj):
        print(f'Send Calc Request To Sub Process:{obj}')
        self.channel.basic_publish(exchange='',
                                   routing_key='rpc_queue',
                                   properties=pika.BasicProperties(reply_to=self.callback_queue, correlation_id=self.corr_id),
                                   body=f'{obj}')
        while self.response is None:
            self.connection.process_data_events()
        return self.response


fibonacci_rpc = ProcessMain()
print(" [x] Requesting fib(30)")
response = fibonacci_rpc.call_sub_process(30)
print(f'Sub Process Result:{response}')
